package com.example.config;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import java.util.HashMap;
import java.util.Map;


public class UserRealm extends AuthorizingRealm {
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //当用户进入需要授权的页面时，进入了这个方法
        System.out.println("执行了=>授权doGetAuthorizationInfo");

        //拿到当前登录的用户
        Subject user = SecurityUtils.getSubject();
        Map currentUser = (Map)user.getPrincipal();//获得认证方法里传来的Map
        String authority = (String)currentUser.get("authority");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //设置当前用户的权限
        info.addStringPermission(authority);

        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //当用户登录时，进入了这个方法
        System.out.println("执行了=>认证doGetAuthenticationInfo");



        //模拟数据库的数据
        Map<String,Object> map = new HashMap<>();
        String name = "朱海斌";
        String password = "123";
        String authority = "user:add";
        map.put("name",name);
        map.put("password",password);
        map.put("authority",authority);

        UsernamePasswordToken uesrToken  = (UsernamePasswordToken) token;
        if(!uesrToken.getUsername().equals(map.get("name"))){
            return null;//代表抛出UnknownAccountException异常
        }

        //密码认证交给shiro，顺便把装载着用户信息的map放到subject中
        return new SimpleAuthenticationInfo(map,password,"");
    }
}
